package cn.lxh.mq.tx;


import cn.lxh.constants.Constants;
import cn.lxh.pojo.domain.PayOrder;
import cn.lxh.pojo.domain.PayOrderProfitsharing;
import cn.lxh.pojo.domain.WxpayFlow;
import cn.lxh.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.Map;

//支付结果-事务监听器
@RocketMQTransactionListener(txProducerGroup= Constants.MQ.TX_PRODUCER_PAY_RESULT)
@Slf4j
public class PayResultTXListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;
    /**
     * 执行本地事务 ；修改支付单，保存支付流水
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        //拿到支付单和流水
        Map<String,Object> map =(Map)arg;
        PayOrder payOrder = (PayOrder) map.get("payOrder");
        WxpayFlow wxpayFlow = (WxpayFlow) map.get("wxpayFlow");
        PayOrderProfitsharing profitSharing = (PayOrderProfitsharing) map.get("profitsharing");
        try {
            log.info("执行本地事务修改支付单 {} - 保存流水 {}",payOrder,wxpayFlow,profitSharing);
            payOrderService.updatePayOrderAndCreateFlow(payOrder,wxpayFlow,profitSharing);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        return null;
    }
}
